<template>
  <div>
    <h3 class="title">多文件上传</h3>
    <div class="border_dot">
      <form id="formtmultiple">
        <input
          ref="fileRef"
          type="file"
          style="display: none"
          multiple
          accept=".png,.jpg,.jpeg,.zip"
        />
      </form>
      <button class="btn select_btn btn_sel_multiple" @click="handleFile">
        选择文件
      </button>
      <button class="btn update_btn btn_up_multiple" @click="handleUpdate">
        上传
      </button>
      <div>请上传PNG/JPG/ZIP类型图片</div>
      <div class="multiple_list_wrap scroll_box" v-if="file.length > 0">
        <div v-for="f in file" :key="f.key">
          <div class="file_item_wrap">
            <span class="file_name">{{ f.filename }}</span>
            <span class="file_remove" @click="handleRemove(f)">移除</span>
          </div>
          <Progress :value="f.progress" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import Progress from "./Progress.vue";
import { readAsDataURL } from "@/utils/index";
import { updateFile } from "@/api/update";
interface IFileList {
  file: File;
  filename: string;
  key: number;
  progress: number;
}
const fileRef = ref<null | HTMLInputElement>(null);
const file = ref<IFileList[]>([]);

async function handleUpdate() {
  if (file.value.length === 0) {
    alert("请选择文件");
    return;
  }
  const selectBtn = document.querySelector(".btn_sel_multiple");
  const updateBtn = document.querySelector(".btn_up_multiple");
  selectBtn?.setAttribute("disabled", "disabled");
  updateBtn?.setAttribute("loading", "loading");
  const files = file.value.map((e) => {
    return new Promise((resolve, reject) => {
      const formData = new FormData();
      formData.append("file", e.file);
      updateFile<FormData, { type: number; path: string }>(formData, {
        onUploadProgress: (ev: ProgressEvent) => {
          e.progress = Math.ceil((ev.loaded / ev.total) * 100);
        },
      })
        .then(resolve)
        .catch(reject);
    });
  });
  try {
    await Promise.all(files);
    alert("上传成功");
  } catch (error) {
    alert("上传失败");
  } finally {
    (document.querySelector("#formtmultiple") as HTMLFormElement).reset();
    file.value = [];
    selectBtn?.removeAttribute("disabled");
    updateBtn?.removeAttribute("loading");
  }
}
function handleFile() {
  fileRef.value?.click();
}
function handleRemove(f: IFileList) {
  file.value = file.value.filter((e) => e.key !== f.key);
}
onMounted(() => {
  fileRef.value?.addEventListener("change", async (ev: Event) => {
    console.log((ev.target as HTMLInputElement).files);
    Array.from((ev.target as HTMLInputElement).files as FileList).forEach(
      (f) => {
        file.value.push({
          progress: 0,
          filename: f.name,
          file: f,
          key: Math.ceil(Math.random() * Date.now()),
        });
      }
    );
  });
});
</script>

<style></style>
